<template>
  <section>
    <van-nav-bar title="慧目之援" fixed placeholder safe-area-inset-top />
  </section>

  <!-- 滚动条 -->
  <section>
    <van-notice-bar scrollable left-icon="volume-o"
      text="我们一直在这里等待着为您提供帮助。请随时告诉我们您需要什么支持，我们会付出全力的为您服务。我们非常重视您的需求，并希望能够为您带来积极的体验。" />
  </section>

  <!-- 未登录时所展示的样子 -->
  <section v-if="!userStore.userInfo.isLogin">
    <img class="theme" src="@/assets/theme.jpg" alt="主题图片">
    <van-divider>您尚未登录</van-divider>

    <footer class="footer-logout">
      <van-button @click="blindRegisterHandler" size="large" type="primary" block
        style="margin-bottom: 2px;">我需要视觉帮助</van-button>
      <van-button @click="volunteerAndBlindPerson(1)" size="large" type="primary" block>我想成为志愿者</van-button>
    </footer>
  </section>

  <!-- 登录后所展示的样子 -->
  <section v-else>
    <!-- 志愿者端 -->
    <matchCom v-if="userStore.userInfo.types === 1">
      <van-divider>请您耐心等待</van-divider>

      <div class="match-vol">
        <img class="match-vol-img" src="@/assets/vol.png" alt="志愿者端图片">
        <van-cell-group inset>
          <van-field style="margin-top: 20px" disabled readonly label="帮助人数" left-icon="smile-o" placeholder="0" />
          <van-field style="margin-top:5px" disabled readonly label="积分" left-icon="gem-o" placeholder="0" />
        </van-cell-group>

        <van-button block type="warning" hairline @click="router.push({ name: 'communityCourse' })">社区使用教程</van-button>
        <van-button block type="primary" @click="router.push({ name: 'learnCallPhone' })">学习如何接听电话</van-button>
      </div>
    </matchCom>

    <!-- 盲人端 -->
    <matchCom v-else>
      <div class="match-blind-person">
        <van-config-provider :theme-vars="buttonVars">
          <div>
            <van-button block type="primary" size="large" @click="clickToCall">致电第一位可用的志愿者</van-button>
          </div>
        </van-config-provider>
        <van-button block type="warning" hairline @click="router.push({ name: 'communityCourse' })">社区使用教程</van-button>
        <van-button block @click="router.push({ name: 'UserFeedback' })">意见反馈</van-button>
      </div>
    </matchCom>

  </section>
</template>

<script setup>
import { useRouter } from "vue-router";
import { showFailToast, showToast } from "vant";
import { onBeforeMount, reactive, ref, watch } from "vue";
import { getStorage } from '@/utils/localStorage';

import usePeerStore from "@/store/peer";
import useUserStore from "@/store/user";
// import useVideoCallMatchStore from "@/store/user/videoCallMatch";
import useVideoCallMatchStore from "../../store/user/VideoCallMatch";


import matchCom from '@/components/matchCom.vue';


let peerStore = usePeerStore();
let userStore = useUserStore();
let router = useRouter();
let matchStore = useVideoCallMatchStore();


let visible = ref(false)

const buttonVars = reactive({
  // --van-button-large-height
  buttonLargeHeight: '50vh',
  buttonPrimaryBackground: '#47e',
  // -van-button-default-font-size
  buttonDefaultFontSize: '10vw'
})

// 跳转到视频界面
function jumpToVideoCallCallingView(calleePeerId) {
  // console.log("jump to video call calling view", calleePeerId)
  if (peerStore.localPeer && peerStore.localPeer.open) {
    if (peerStore.dataConnection) {
      // showToast("currently busy");
      showToast("连接失败...");
    } else {
      router.push({
        path: "/video-call-calling-view",
        query: {
          calleePeerId
        }
      });
    }
  } else {
    // showToast("local peer not opened");
    showToast("本地初始化失败...");
  }
}

// 监听 是否获取到 peerId 
watch(() => userStore.userInfo.preeJsid, (newVal) => {
  // userPeerId.value = newVal
  matchStore.videoCallAttr.peerId = newVal
  if (getStorage('userStore') && getStorage('userStore').userInfo.isLogin) {
    getVolunteerPeerId()
  }
})

onBeforeMount(() => {
  if (getStorage('userStore')) {
    visible.value = true
    // userTypes.value = userStore.userInfo.types
    matchStore.updateTypes(userStore.userInfo.types)
  }
})

// 获取志愿者 peerId
let socket = null
function getVolunteerPeerId() {
  const socketUrl = `wss://app6686.acapp.acwing.com.cn/peerServerEndpoint/${matchStore.videoCallAttr.peerId}/${matchStore.videoCallAttr.types}`

  socket = new WebSocket(socketUrl);

  socket.onopen = () => {
    matchStore.videoCallAttr.socket = socket
  }

  socket.onclose = () => {
    // console.log('socket closed')
    showFailToast('连接已断开，请稍后再试')
  }


  /*
  if (matchStore.videoCallAttr.volPeerId) {
    jumpToVideoCallCallingView(matchStore.videoCallAttr.volPeerId)
  } else {
    showFailToast('暂无志愿者，请稍后再试')
  }
  */
  socket.onmessage = msg => {
    // console.log(msg.data)
    // alert(msg.data)
    if (msg.data !== '-1000' && (typeof msg.data === "string")) {
      matchStore.updateVolPeerId(msg.data)
      jumpToVideoCallCallingView(matchStore.videoCallAttr.volPeerId)
    } else if (msg.data === '-1000') {
      showFailToast('暂无志愿者，请稍后再试')
    }
  }
}

const volunteerAndBlindPerson = (type) => {
  router.push({ name: 'UserRegister', params: { types: type } })

}

const blindRegisterHandler = () => {
  userStore.blindRegisterTo()
}

// 点击呼叫
const clickToCall = () => {
  matchStore.videoCallAttr.socket.send(JSON.stringify({
    message: 'startMatch'
  }))
}
</script>

<style scoped lang="scss">
.match-vol,
.match-blind-person {
  margin: 0 5vw;

  .match-vol-img {
    width: 90vw;
  }

  & button {
    margin-top: 20px;
  }
}

.theme {
  width: 100vw;
}

.footer-logout {
  width: 90vw;
  margin: 0 5%;
  position: fixed;
  bottom: 3.9rem;
}
</style>